﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Xml;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Security.Cryptography;

namespace NKD07.Admin
{
    public partial class publisher : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // show thông tin c?a nhà s?n xu?t
            LoadDetailPublisher();
            // ?n cái key di
            key.Visible = false;
        }
        private void LoadDetailPublisher()
        {
            try
            {
                int publisherID = int.Parse(Request.QueryString["publisherID"]);
                Classes.manufacturer manu = new Classes.manufacturer();
                DataTable table = manu.GetManufacturerByID(publisherID);
                if (table == null || table.Rows.Count == 0)
                {
                    Response.Redirect("publisher.aspx");
                }
                //dtwPublisherDetails.DataSource = table;
                //dtwPublisherDetails.DataBind();

                // l?y username, password d? login webservice
                usernameAccess.Text = table.Rows[0]["usernamAccess"].ToString();
                passwordAccess.Text = table.Rows[0]["passwordAccess"].ToString();
                lblNamePublisher.Text = table.Rows[0]["name"].ToString();
                lblAddressPublisher.Text = table.Rows[0]["address"].ToString();
                lblCityPublisher.Text = table.Rows[0]["city"].ToString();
                lblPhonePublisher.Text = table.Rows[0]["phone"].ToString();
                lblMailPublisher.Text = table.Rows[0]["email"].ToString();
            }
            catch (Exception)
            {
                Response.Redirect("publisher.aspx");
                String.Format("{0}", Eval("id"));
            }
        }

        // button login
        protected void Button1_Click(object sender, EventArgs e)
        {


            string par1 = usernameAccess.Text;
            string par2 = passwordAccess.Text;
            string address = "http://localhost:59363/Service1.asmx";
            string function = "loginNSX";

            XmlNode _node = (XmlNode)WebserviceInvoker.WSInvoker.CallWebService(address, "Service1", function, new object[] { par1, par2 });
            key.Text = _node.FirstChild.Value.ToString();

            // login thành công


            string functionC = "getCategory";
            string par1C = _node.FirstChild.Value.ToString();
            string par2C = usernameAccess.Text;
            XmlDocument _doc = new XmlDocument();

            XmlNode _nodeCategories = (XmlNode)WebserviceInvoker.WSInvoker.CallWebService(address, "Service1", functionC, new object[] { par1C, par2C });

            _doc.AppendChild(_doc.ImportNode(_nodeCategories, true));

            XmlDataSource xmlDS = new XmlDataSource();
            xmlDS.ID = "xmlDSID";
            xmlDS.Data = _doc.InnerXml;
            xmlDS.XPath = "root/item";

            dtlCategories.DataSource = xmlDS;
            dtlCategories.DataBind();


            // lấy danh sách sách mới nhất

            lbCategoryName.Text = "Lastest products";

            //string address = "http://localhost:59363/Service1.asmx";
            string functionS = "getProductLastest"; // tìm kiếm sản phẩm theo tên
            string par1S = key.Text;
            string par2S = usernameAccess.Text;
   

            XmlDocument _docS = new XmlDocument();
            XmlNode _nodeProductsS = (XmlNode)WebserviceInvoker.WSInvoker.CallWebService(address, "Service1", functionS, new object[] { par1S, par2S });
            _docS.AppendChild(_docS.ImportNode(_nodeProductsS, true));

            XmlDataSource xmlDSP = new XmlDataSource();
            xmlDSP.ID = "xmlDSPIDLastest" + par1S;

            xmlDSP.Data = _docS.InnerXml;
            xmlDSP.XPath = "root/item";

            btlLastestProduct.DataSource = xmlDSP;
            btlLastestProduct.DataBind();
            Panel3.Visible = false;


            dtlProducts.Visible = false;
            dtlResultSearch.Visible = false;
            btlLastestProduct.Visible = true;


        }


        // select categories
        protected void m_Click(object sender, EventArgs e)
        {

            Button bt = (Button)sender;
            lbCategoryName.Text = bt.Text;

            string address = "http://localhost:59363/Service1.asmx";
            string function = "getProduct"; // tìm kiếm sản phẩm theo danh mục
            string par1 = key.Text;
            string par2 = usernameAccess.Text;
            int    par3 = int.Parse(bt.CommandArgument);

            XmlDocument _doc = new XmlDocument();
            XmlNode _nodeProducts = (XmlNode)WebserviceInvoker.WSInvoker.CallWebService(address, "Service1", function, new object[] { par1, par2, par3 });
            _doc.AppendChild(_doc.ImportNode(_nodeProducts, true));

            XmlDataSource xmlDSP = new XmlDataSource();
            xmlDSP.ID = "xmlDSPID"+par3; 

            xmlDSP.Data = _doc.InnerXml;
            xmlDSP.XPath = "root/item";

            dtlProducts.DataSource = xmlDSP;
            dtlProducts.DataBind();
            Panel3.Visible = false;

            dtlProducts.Visible = true;
            dtlResultSearch.Visible = false;
            btlLastestProduct.Visible = false;
            
        }

        // buy
       
        protected void btn_Click(object sender, EventArgs e)
        {
            Button bt = (Button)sender;
            lbCategoryName.Text = bt.Text;
            buyOK.CommandArgument = bt.CommandArgument;
            Panel3.Visible = true;


            // tạo ngẫu nhiên 1 số
            Random rd = new Random();
            int number = rd.Next(0, 10000000);
            System.Security.Cryptography.MD5CryptoServiceProvider md5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] hashedBytes;
            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(number.ToString()));
            string confirm = ConvertToHex(hashedBytes);

            lblconfirm.Text = confirm;
        }
        public string ConvertToHex(byte[] asciiString)
        {
            string hex = "";
            foreach (byte c in asciiString)
            {
                int tmp = c;
                hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
            }
            return hex;
        }

        protected void buyOK_Click(object sender, EventArgs e)
        {
            

            Button bt = (Button)sender;
          

            string address = "http://localhost:59363/Service1.asmx";
            string function = "buy";

            string iKey = key.Text;
            string username = usernameAccess.Text;
            float Iprice = int.Parse(txtPrice.Text);
            int Inumber = int.Parse(txtNumber.Text);
            int Ilongterm = Convert.ToInt32(ckLongTerm.Checked);
            int Iproduct = int.Parse(bt.CommandArgument);
            string IdateBegin = txtDateBegin.Text;
            string IdateEnd = txtDateEnd.Text;
            string confirm = lblconfirm.Text;
            int Imin = 0;

            int result = (int)WebserviceInvoker.WSInvoker.CallWebService(address, "Service1", function, new object[] { iKey, username, Iprice, Inumber, Ilongterm, Iproduct, IdateBegin, IdateEnd, Imin, confirm });

            txtDateEnd.Text = "";
            txtDateBegin.Text = "";
            ckLongTerm.Checked = false;
            txtNumber.Text = "";
            txtPrice.Text = "";
            Panel3.Visible = false;

            // insert thông tin vào bản ManufacturerContract
            SqlConnection cn = new SqlConnection();
            cn.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["BookStoreDBConnectionString"].ToString();
            //ConfigurationManager.ConnectionStrings["BookStoreDBConnectionString"].ConnectionString
            SqlCommand cmd = new SqlCommand("SELECT * FROM Manufacturer WHERE username = '" + username + "'", cn);
            cn.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            rdr.Read();
            int MidManufacturer = Convert.ToInt32(rdr["id"].ToString());
            if (rdr.HasRows != false) {
                cmd = new SqlCommand("SELECT * FROM Product WHERE Mapping = @mapping", cn);
                cmd.Parameters.Add("@mapping", SqlDbType.Int);
                cmd.Parameters["@mapping"].Value = Iproduct;
                rdr = cmd.ExecuteReader();
                rdr.Read();
                int MidProduct = 0;
                if (rdr.HasRows == false)
                {
                    ///add product information
                    MidProduct = 1;
                }
                else
                {
                    MidProduct = Convert.ToInt32(rdr["id"].ToString());
                }
                cmd = new SqlCommand("INSERT INTO ManufacturerContract (idManufacturer, idProduct, longTerm, dateEnd, min, dateBegin, minStock, price, confirm) VALUES (@SidManufacturer, @SidProduct, @SlongTerm, @SdateEnd, @Smin, @SdateBegin, @SminStock, @Sprice, @Sconfirm)", cn);
                cmd.Parameters.Add("@SidManufacturer", SqlDbType.Int);
                cmd.Parameters["@SidManufacturer"].Value = MidManufacturer;

                cmd.Parameters.Add("@SidProduct", SqlDbType.Int);
                cmd.Parameters["@SidProduct"].Value = MidProduct;

                cmd.Parameters.Add("@SlongTerm", SqlDbType.Int);
                cmd.Parameters["@SlongTerm"].Value = Iprice;

                cmd.Parameters.Add("@SdateEnd", SqlDbType.Date);
                cmd.Parameters["@SdateEnd"].Value = IdateEnd;

                cmd.Parameters.Add("@Smin", SqlDbType.Int);
                cmd.Parameters["@Smin"].Value = Inumber;

                cmd.Parameters.Add("@SdateBegin", SqlDbType.Date);
                cmd.Parameters["@SdateBegin"].Value = IdateBegin;

                cmd.Parameters.Add("@SminStock", SqlDbType.Int);
                cmd.Parameters["@SminStock"].Value = Imin;

                cmd.Parameters.Add("@Sprice", SqlDbType.Float);
                cmd.Parameters["@Sprice"].Value = Iprice;

                cmd.Parameters.Add("@Sconfirm", SqlDbType.Int);
                cmd.Parameters["@Sconfirm"].Value = confirm;
                cmd.ExecuteNonQuery();
            }
            cn.Close();


        }

        protected void tnSearch_Click(object sender, EventArgs e)
        {
            lbCategoryName.Text = "Result to search with key ' " + keyWord.Text + "'";

            string address = "http://localhost:59363/Service1.asmx";
            string function = "getProductByName"; // tìm kiếm sản phẩm theo tên
            string par1 = key.Text;
            string par2 = usernameAccess.Text;
            string par3 = keyWord.Text;

            XmlDocument _doc = new XmlDocument();
            XmlNode _nodeProducts = (XmlNode)WebserviceInvoker.WSInvoker.CallWebService(address, "Service1", function, new object[] { par1, par2, par3 });
            _doc.AppendChild(_doc.ImportNode(_nodeProducts, true));

            XmlDataSource xmlDSP = new XmlDataSource();
            xmlDSP.ID = "xmlDSPIDSearch" + par3;

            xmlDSP.Data = _doc.InnerXml;
            xmlDSP.XPath = "root/item";

            dtlResultSearch.DataSource = xmlDSP;
            dtlResultSearch.DataBind();
            Panel3.Visible = false;

            dtlProducts.Visible = false;
            dtlResultSearch.Visible = true;
            btlLastestProduct.Visible = false;
        }
        



    }
}